﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using SmartForm.Common;
using SmartForm.Rule;
using SmartlForm;
using SmartlForm.Model;

namespace SmartForm
{
    public partial class AppMain : Form
    {
        public AppMain()
        {
            InitializeComponent();
        }

        public void initInstaller() { }

        private void EndProcess()
        {
            //关掉可能没有关闭掉的残留进程
            var processList = ComputerInfo.GetAllProcesses().ToList().FindAll(d => d.ProcessName.IndexOf("CefSharp.BrowserSubprocess") > -1);
            if (processList != null && processList.Count > 0)
            {
                foreach (var item in processList)
                {
                    ComputerInfo.EndProcess(item.Id);
                }
            }
        }

        private void App_Load(object sender, EventArgs e)
        {
            //关掉残留进程
            EndProcess();

            this.BeginInvoke(new Action(() =>
            {
                this.Hide();
                this.Opacity = 1;
            }));
            //进入登陆页

            string url = @"\page\pages\samples\login.html";
            BowContainer loginForm = new BowContainer("登录", url);
            loginForm.Show();

            //BigForm bigForm = new BigForm();
            //List<SystemRule> systemRuleList = new List<SystemRule>();
            //SystemRule systemRule = new SystemRule();

            ////大表单 
            //bigForm.LoginToken = "123456";
            //bigForm.SystemIds = new List<string>() { "1" };
            //bigForm.TypeId = "101";
            //bigForm.FormOptionList = new List<FormOption>()
            //{
            //    //大表单配置
            //    //new FormOption(){ Name="ProposalCategoryId",Value="7796771317302272",InputType=InputType.Text, Title="建议类型"},
            //    //new FormOption(){ Name="Title",Value="智能表单标题",InputType=InputType.Text, Title="建议标题"},
            //    //new FormOption(){ Name="Content",Value="智能表单内容",InputType=InputType.Text, Title="建议内容"},
            //};

            ////系统规则
            //systemRule.ID = "1";
            //systemRule.SystemId = "1";
            //systemRule.TypeId = "101";
            //systemRule.Account = "13389669273";
            //systemRule.Password = "zlinkgroup2018";
            //systemRule.LoginUrl = "https://www.baidu.com";
            //systemRule.LoginJS = new List<ExecuteJS>() { 
            //    //百度贴吧提问
            //    new ExecuteJS() { JS = "$('a.lb').click();", Second = 1 }, //点击登录
            //    new ExecuteJS() { JS = "return $('#TANGRAM__PSP_10__qrcode').is(':visible');", Second = 1,}, //延迟判断
            //    new ExecuteJS() { JS = "document.getElementById('TANGRAM__PSP_10__footerULoginBtn').click();", Second = 1 }, //点击         
            //    new ExecuteJS() { JS = " return $('#passport-login-pop-api').is(':visible');", Second = 1 }, //延迟判断
            //    new ExecuteJS() { JS = "$('#TANGRAM__PSP_10__userName').val('$account');", Second = 1 }, //账号
            //    new ExecuteJS() { JS = "$('#TANGRAM__PSP_10__password').val('$password');", Second = 1 }, //密码
            //    new ExecuteJS() { JS = "document.getElementById('TANGRAM__PSP_10__submit').click();", Second = 1 }, //登录
            //    new ExecuteJS() { JS = "location.href='https://zhidao.baidu.com/new?word=&ie=GBK'", Second = 3 }, //提问页面
            //};

            //systemRule.FormOptionJSList = new List<FormOptionJS>()
            //{
            //    new FormOptionJS(){  JS="document.getElementById('title-area').value='$value';",Name="Title", Value="请问智能表单填写怎么做？"},
            //    new FormOptionJS(){  JS="document.getElementById('content-area').value='$value';",Name="Content", Value="工作中有很多重复的工作，请问智能表单填写怎么做？"},
            //    new FormOptionJS(){  JS="document.getElementsByClassName('cb-status')[0].click();",Name="Status",Second=1},
            //    new FormOptionJS(){  JS="document.getElementById('submit-btn').click();", Value="智能表单 - 发表按钮",Submit=true,Completed=true},
            //};

            //systemRuleList.Add(systemRule);
            //systemRule = new SystemRule();
            ////系统规则
            //systemRule.ID = "1";
            //systemRule.SystemId = "1";
            //systemRule.TypeId = "101";
            //systemRule.Account = "18223277005";
            //systemRule.Password = "1234567";
            //systemRule.LoginUrl = "http://zhdj.zlinkgroup.com/";
            //systemRule.LoginJS = new List<ExecuteJS>() {
            //    //智慧党建
            //    new ExecuteJS() { JS = "document.getElementsByName('mobile')[0].value='18223277003';", Second = 1 },
            //    new ExecuteJS() { JS = "document.getElementsByName('password')[0].value='1234567';", Second = 1 },
            //    new ExecuteJS() { JS = "document.getElementById('submit_btn').click();", Second = 1 },
            //    new ExecuteJS() { JS = "return $('#manage').is(':visible');", Second = 3 },
            //    new ExecuteJS() { JS = "location.href='http://zhdj.zlinkgroup.com/page/user/module/feedback/add.html'", Second = 3 }
            //};

            //systemRule.FormOptionJSList = new List<FormOptionJS>()
            //{
            //    new FormOptionJS(){  JS="document.getElementById('CategoryId').value='$value'",Name="ProposalCategoryId", Value="7796771317302272"},
            //    new FormOptionJS(){  JS="document.getElementsByName('Title')[0].value='$value'",Name="Title", Value="智能表单标题"},
            //    new FormOptionJS(){  JS="document.getElementsByName('Content')[0].value='$value'",Name="Content", Value="智能表单填写内容"},
            //    new FormOptionJS(){  JS="document.getElementById('btnSave').click()", Value="智能表单 - 发表按钮",Submit=true,Completed=true},
            //};
            //systemRuleList.Add(systemRule);
            //TaskRun(bigForm, systemRuleList, 0);
        }
        static bool Completed = false;

        static void TaskRun(BigForm bigForm, List<SystemRule> systemRuleList, int index = 0)
        {
            SystemRule systemRule = systemRuleList[index];
            //可以判断系统使用浏览器版本
            MainChrome mc = new MainChrome(systemRule);
            mc.Completed += TaskCompleted;
            Completed = false;
            mc.Show();
            if (systemRuleList.Count - 1 > index)
            {
                //等待完成后进行下一个任务
                WaitTaskCompleted();
                TaskRun(bigForm, systemRuleList, index + 1);
            }
        }

        /// <summary>
        /// 任务完成回调
        /// </summary>
        static void TaskCompleted()
        {
            Completed = true;
        }


        /// <summary>
        /// 等待当前任务完成
        /// </summary>
        static void WaitTaskCompleted()
        {
            if (!Completed)
            {
                Delay.DelaySecond(1);
                WaitTaskCompleted();
            }
        }

        private void toolStripMenuItem_exit_Click(object sender, EventArgs e)
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要退出吗?", "退出系统", messButton);
            if (dr == DialogResult.OK)
            {
                close();
            }
        }

        public void close()
        {
            try
            {
                this.Visible = false;
                Environment.Exit(Environment.ExitCode);
                this.Dispose();
                Application.Exit();
            }
            catch (Exception ex)
            {
                Environment.Exit(0);
            }
        }

        private void appNotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            bool exits = false;
            foreach (Form f in Application.OpenForms)
            {
                if (f.Text.Equals("工蜂引流") && SmartlForm.NetJs.BowContainer.account != null)
                {
                    f.Visible = true;
                    f.WindowState = FormWindowState.Maximized;
                    f.Activate();
                    exits = true;
                    break;
                }
            }
            if (!exits)
            {
                //新开 
                BowContainer bow = new BowContainer(new FormPar() { name = "app", windowMax = true, windowMin = false, max = true, min = true, display = true, title = "工蜂引流", url = "\\\\page\\\\index.html", width = 480, height = 600, minWidth = 1000, minHeight = 600 });
                bow.Show();
            }
        }
    }
}
